package com.skydroid.demo.helper

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.view.*
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import android.widget.VideoView
import com.skydroid.demo.ui.activity.MainActivity
import com.skydroid.demo.R
import com.skydroid.demo.utils.DensityUtil

object LiveWindowHelper {

    //布局参数.
    private var params: WindowManager.LayoutParams? = null

    //实例化的WindowManager.
    private var windowManager: WindowManager? = null
    private var statusBarHeight = -1
    private var toucherLayout: FrameLayout? = null
    private var imageViewClose: ImageView? = null

    private const val count = 0 //点击次数

    private const val firstClick: Long = 0 //第一次点击时间

    private const val secondClick: Long = 0 //第二次点击时间


    private var start_X = 0f
    private var start_Y = 0f


    // 记录上次移动的位置
    private var lastX = 0f
    private var lastY = 0f
    private var offset = 0

    // 是否是移动事件
    private var isMoved = false

    /**
     * 两次点击时间间隔，单位毫秒
     */
    private const val totalTime = 1000

    private var isInit = true


    @SuppressLint("ClickableViewAccessibility")
    fun initLive(context: Context) {
        try {
            windowManager =
                context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            //赋值WindowManager&LayoutParam.
            params = WindowManager.LayoutParams()
            //设置type.系统提示型窗口，一般都在应用程序窗口之上.
            if (Build.VERSION.SDK_INT >= 26) { //8.0新特性
                params!!.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                params!!.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
            }
            //设置效果为背景透明.
            params!!.format = PixelFormat.RGBA_8888
            //设置flags.不可聚焦及不可使用按钮对悬浮窗进行操控.
            params!!.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            //设置窗口坐标参考系
            params!!.gravity = Gravity.LEFT or Gravity.TOP
            //用于检测状态栏高度.
            val resourceId = context.resources.getIdentifier(
                "status_bar_height",
                "dimen", "android"
            )
            if (resourceId > 0) {
                statusBarHeight = context.resources.getDimensionPixelSize(resourceId)
            }
            offset = DensityUtil.dp2px(context, 2F) //移动偏移量
            //设置原点
            params!!.x = getScreenWidth(context) - DensityUtil.dp2px(context, 170F)
            params!!.y = getScreenHeight(context) - DensityUtil.dp2px(context, (100 + 72).toFloat())
            //设置悬浮窗口长宽数据.
            params!!.width = DensityUtil.dp2px(context, 180F)
            params!!.height = DensityUtil.dp2px(context, 100F)

            //获取浮动窗口视图所在布局.
            toucherLayout = FrameLayout(context)
            var v = TextView(context)
            v.height = 300
            v.width = 300
            v.setBackgroundResource(R.color.colorAccent)
            v.text = "悬浮窗"
//            val playerView = AliyunVodPlayerView(context)
//            playerView.initVideoView(true)
//            playerView.setAutoPlay(true)
//            playerView.setKeepScreenOn(true)
//            playerView.setTitleBarCanShow(false)
//            playerView.setControlBarCanShow(false)
//            val alsb: AliyunLocalSource.AliyunLocalSourceBuilder = AliyunLocalSourceBuilder()
//            alsb.setSource("http://ivi.bupt.edu.cn/hls/cctv3hd.m3u8")
//            val localSource: AliyunLocalSource = alsb.build()
//            playerView.setLiveSource(localSource)

            toucherLayout!!.addView(
                v, ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
            imageViewClose = ImageView(context)
            imageViewClose!!.setImageResource(R.mipmap.icon_close)
            val layoutParams: FrameLayout.LayoutParams = FrameLayout.LayoutParams(
                DensityUtil.dp2px(context, 16F), DensityUtil.dp2px(context, 16F)
            )
            layoutParams.gravity = Gravity.TOP or Gravity.RIGHT
            layoutParams.rightMargin = DensityUtil.dp2px(context, 3F)
            layoutParams.topMargin = DensityUtil.dp2px(context, 3F)
            imageViewClose!!.layoutParams = layoutParams
            toucherLayout!!.addView(imageViewClose, layoutParams)


            //添加toucherlayout
            if (isInit) {
                windowManager!!.addView(toucherLayout, params)
            } else {
                windowManager!!.updateViewLayout(toucherLayout, params)
            }

            //主动计算出当前View的宽高信息.
            toucherLayout!!.measure(
                View.MeasureSpec.UNSPECIFIED,
                View.MeasureSpec.UNSPECIFIED
            )

            //处理touch
            toucherLayout?.setOnTouchListener { _, event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        isMoved = false
                        // 记录按下位置
                        lastX = event.rawX
                        lastY = event.rawY
                        start_X = event.rawX
                        start_Y = event.rawY
                    }
                    MotionEvent.ACTION_MOVE -> {
                        isMoved = true
                        // 记录移动后的位置
                        val moveX = event.rawX
                        val moveY = event.rawY
                        // 获取当前窗口的布局属性, 添加偏移量, 并更新界面, 实现移动
                        params!!.x += (moveX - lastX).toInt()
                        params!!.y += (moveY - lastY).toInt()
                        if (toucherLayout != null) {
                            windowManager!!.updateViewLayout(toucherLayout, params)
                        }
                        lastX = moveX
                        lastY = moveY
                    }
                    MotionEvent.ACTION_UP -> {
                        val fmoveX = event.rawX
                        val fmoveY = event.rawY
                        if (Math.abs(fmoveX - start_X) < offset && Math.abs(
                                fmoveY - start_Y
                            ) < offset
                        ) {
                            isMoved = false
                            val intent = Intent(context, MainActivity::class.java)
                            context.startActivity(intent)
                        } else {
                            isMoved = true
                        }
                    }
                }
                // 如果是移动事件, 则消费掉; 如果不是, 则由其他处理, 比如点击
                isMoved
            }

            //删除
            imageViewClose!!.setOnClickListener { remove(context) }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        isInit = false
    }

    private fun remove(context: Context) {
        if (windowManager != null && toucherLayout != null) {
            windowManager!!.removeView(toucherLayout)
            isInit = true
        }
    }

    /**
     * 获取屏幕宽度(px)
     */
    private fun getScreenWidth(context: Context): Int {
        return context.resources.displayMetrics.widthPixels
    }

    /**
     * 获取屏幕高度(px)
     */
    private fun getScreenHeight(context: Context): Int {
        return context.resources.displayMetrics.heightPixels
    }

}